from logging import getLogger
from urllib import quote

from zope import schema
from zope.component import getMultiAdapter
from zope.formlib import form
from zope.interface import implements

from plone.app.portlets.portlets import base
from plone.memoize import ram, instance
from plone.memoize.compress import xhtml_compress
from plone.portlets.interfaces import IPortletDataProvider
from plone.app.portlets.cache import render_cachekey
from plone.app.layout.navigation.root import getNavigationRootObject

from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone import PloneMessageFactory as _

from meercat.ui.plone.browser.portlets.facetBase import BaseFacetRenderer



log = getLogger('meercat.ui.plone.browser.portlets.facetDate')

class IFacetDatePortlet(IPortletDataProvider):
    
    label = schema.TextLine(title=_(u'The displayed title for the facet'),
                            required=True)
    
    field = schema.TextLine(title=_(u'The name of the field to facet on'),
                            required=True)
    
    start = schema.TextLine(title=_(u'Start date/time for the range'),
                             description=_(u'See: http://wiki.apache.org/solr/SimpleFacetParameters#Date_Faceting_Parameters'),
                             required=True)
    
    end = schema.TextLine(title=_(u'End date/time for the range'),
                          description=_(u'See: http://wiki.apache.org/solr/SimpleFacetParameters#Date_Faceting_Parameters'),
                          required=True)
    
    gap = schema.TextLine(title=_(u'Gap for subranges'),
                          description=_(u'See: http://wiki.apache.org/solr/SimpleFacetParameters#Date_Faceting_Parameters'),
                          required=True)
    
    hardend = schema.Bool(title=_(u'Hard end for ranges'),
                          description=_(u'See: http://wiki.apache.org/solr/SimpleFacetParameters#Date_Faceting_Parameters'),
                          required=False)
    
    before = schema.Bool(title=_(u'Include before range'),
                         required=False)
    
    after = schema.Bool(title=_(u'Include after range'),
                        required=False)
    
    between = schema.Bool(title=_(u'Include between range'),
                          required=False)
    
class Assignment(base.Assignment):
    implements(IFacetDatePortlet)
    
    def __init__(self, label, field, start, end, gap, hardend=False,
                 before=False, after=False, between=False):
        self.label = label
        self.field = field
        self.start = start
        self.end = end
        self.gap = gap
        self.hardend = hardend
        self.before = before
        self.after = after
        self.between = between
    
    @property
    def title(self):
        return _(u"Facet Date: ") + self.label

class Renderer(BaseFacetRenderer):
    
    @instance.memoize
    def getQueryParameters(self):
        params = super(Renderer,self).getQueryParameters()
        
        if not params:
            log.debug('No parameters received from super call')
            return None
        
        params['facet.date'] = self.data.field
        params['facet.date.start'] = self.data.start
        params['facet.date.end'] = self.data.end
        params['facet.date.gap'] = self.data.gap
        
        if self.data.hardend:
            params['facet.date.hardend'] = 'true'
        
        params['facet.date.other'] = []
        
        if self.data.before:
            params['facet.date.other'].append('before')
        
        if self.data.between:
            params['facet.date.other'].append('after')
        
        if self.data.after:
            params['facet.date.other'].append('between')
        
        if len(params['facet.date.other']) == 0:
            del params['facet.date.other']
        
        return params
    
    def getFacets(self):
        facet_counts = self.getFacetCounts()
        
        if not facet_counts:
            log.debug('No facet counts')
            return None
        
        log.info(unicode(facet_counts))
        return []
        
        counts = facet_counts.get('facet_fields',{}).get(self.data.field,{})
        facets = []
        
        for value,count in counts.iteritems():
            facets.append({'value':value,
                           'count':count,
                           'url':self.view.getUrlWithParams(remove=['page'],
                                                            replace=False,
                                                            fq='%s:"%s"' % (self.data.field,
                                                                            value,))})
        
        if self.data.sort:
            facets.sort(key=lambda f: f['value'].lower())
        else:
            facets.sort(key=lambda f: f['count'], reverse=True)
        
        return facets

class AddForm(base.AddForm):
    form_fields = form.Fields(IFacetDatePortlet)
    label = _(u"Add Facet Date Portlet")
    description = _(u"This portlet lists a date facet for a field from a search.")
    
    def create(self, data):
        return Assignment(label=data.get('label'),
                          field=data.get('field'),
                          start=data.get('start'),
                          end=data.get('end'),
                          gap=data.get('gap'),
                          hardend=data.get('hardend',False),
                          before=data.get('before',False),
                          after=data.get('after',False),
                          between=data.get('between',False))

class EditForm(base.EditForm):
    form_fields = form.Fields(IFacetDatePortlet)
    label = _(u"Edit Facet Date Portlet")
    description = _(u"This portlet lists a date facet for a field from a search.")
